package com.baomidou.plugin.idea.mybatisx.advance.processor.clazz;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.plugin.idea.mybatisx.advance.util.PsiMethodUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * 给po的每个属性都生成一个notNull,isNull,orderByDesc,orderByAsc方法
 * @author wanglei
 */
public class NoneParamProcessor extends AbstractMPOnceMethodGenClassProcessor {

    private static final Logger log = Logger.getInstance(NoneParamProcessor.class.getName());

    public static Set<String> ORDINARY_METHOD_NAMES = new HashSet<>();


    static {
        ORDINARY_METHOD_NAMES.add("notNull");
        ORDINARY_METHOD_NAMES.add("isNull");
        ORDINARY_METHOD_NAMES.add("orderByDesc");
        ORDINARY_METHOD_NAMES.add("orderByAsc");
    }

    private static final String CLASS_NAME = TableName.class.getName();

    public static final String METHOD_NAME = "noneParam";

    public NoneParamProcessor() {
        super(CLASS_NAME, PsiMethod.class);
    }

    @Override
    String getMethodName() {
        return METHOD_NAME;
    }

    @NotNull
    public Collection<PsiMethod> createToStringMethod(@NotNull PsiClass psiClass, @NotNull PsiElement psiNavTargetElement) {
        List<PsiMethod> methods = new ArrayList<>();

        for (String methodName : ORDINARY_METHOD_NAMES) {
            methods.addAll(genMethodForFields(psiClass, psiNavTargetElement, methodName));
        }
        return methods;
    }

    /**
     * 给一个字段生成方法
     *
     * @param psiClass            class
     * @param psiNavTargetElement
     * @param methodName          方法名
     * @return
     */
    public List<PsiMethod> genMethodForFields(@NotNull PsiClass psiClass, @NotNull PsiElement psiNavTargetElement, String methodName) {
        List<PsiMethod> methods = new ArrayList<>();

        final StringBuilder builder = new StringBuilder();
        try {
            builder.append("public " + psiClass.getName() + " " +  methodName + "(){return this;} ");
            methods.add(PsiMethodUtil.createMethod(psiClass, builder.toString(), psiNavTargetElement));
        } finally {
            //StringBuilderSpinAllocator.dispose(builder);
        }
        return methods;
    }
}
